//
//  newCreatOneNovelViewController.m
//  shusheng
//
//  Created by rimi on 16/7/12.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "NewCreatOneNovelViewController.h"
#import "Nove.h"

/**< 打印路径 */
#define NSLOG_DOCUMENTS_PATH  NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject);

/**< 沙盒地址 */
#define DOCUMENT_PATH NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject
/**< 文件管理类 */
#define DEFAULT_FILEMANAGER [NSFileManager defaultManager]




//static NSString *const PlistName     = @"/UserNovelsPlistList.plist";


@interface NewCreatOneNovelViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *pic;
@property (weak, nonatomic) IBOutlet UITextField *novelId;//小说id
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *synopsis;//简介

@property (nonatomic, strong) UIImage *btnImage;
@property (nonatomic, strong) UIAlertController *alertController;//表单
@property (nonatomic, strong) UIImagePickerController *imagePickerController;//相册拾取器
@end

@implementation NewCreatOneNovelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化相册选择器
    _imagePickerController = [[UIImagePickerController alloc] init];
    
    
    
}


- (IBAction)btn:(UIButton *)sender {
    
    switch (sender.tag - TAG_BTN) {
        case 0:
            //返回与取消
            NSLog(@"返回与取消");
            [MBProgressHUD showSuccess:@"离开"];
            [self remove];
            break;
        case 1:
            //照片相册
            NSLog(@"照片相册");
            _alertController = self.alertController;//表单
            [self presentViewController:self.alertController animated:YES completion:nil];
            
            break;
        case 2:
            //确定添加
            NSLog(@"确定添加");
            
            
            //获得界面数据
            //本地
            //服务器同步。
            [self haveData];
           
            
            break;
       
            
        default:
            break;
    }
    
}




//获取界面的数据信息
- (void)haveData{

    if (_novelId.text.length == 0 || _name.text.length == 0) {//未命名
        NSLog(@"未有小说ID或未命名");
        [MBProgressHUD showError:@"未有小说ID或未命名"];
        return;
        
    }else if ([self isExisting:_novelId.text]){//防止相同ID存在
        NSLog(@"小说ID重复");//yes~>名字相同，
        [MBProgressHUD showError:@"小说ID重复"];
        return;
        
    }else{
        //存储操作
        [self save];
        //服务器同步
        [self networkSynchronization];//网络同步
//        [self remove];
    }
    
}
//遍历已有小说名
- (BOOL)isExisting:(NSString *)novelId{
    //调用查询
    //得到ID
    //对比
    
    NSArray *novels = [self read];//查看操作
    NSDictionary *dic = [NSDictionary dictionary];
    for (int i = 0; i < novels.count ; i++) {
           dic = novels[i];
           NSString *n = [dic objectForKey:@"novelId"];
        if ([novelId isEqualToString:n]) {
            NSLog(@"小说ID重复");
            return YES;
        }
    }
    NSLog(@"小说ID可用");
    return NO;
}

//存储操作
- (void)save{
    
    //获取沙盒（plist）路径,拼接
    NSString * path = [DOCUMENT_PATH stringByAppendingString:[NSString stringWithFormat:@"%@UserNovelsPlistList.plist",[AVUser currentUser].objectId]];
    
    //判断plist文件路径是否存在~如果存在，则根据plist文件路径初始化根数组（代表有数据，取出原有数据再存，才不会覆盖==获取原有的数据）；否则直接初始化根数组。
    NSMutableArray * rootArr = nil;
    if ([DEFAULT_FILEMANAGER fileExistsAtPath:path ]) {
        rootArr=[NSMutableArray  arrayWithContentsOfFile:path];
    }else{
        rootArr =[@[]mutableCopy];
    }
    
    //打包用户信息
    NSDictionary * infoDict = @{@"userId":[AVUser currentUser].objectId,@"novelId":self.novelId.text,@"name":self.name.text,@"synopsis":self.synopsis.text,@"time":[ToolOfBasic nowTime]};//,@"pic":_pic.currentBackgroundImage
    
    //将用户信息存到根数组
    [rootArr insertObject:infoDict atIndex:0];
    NSLog(@"%@",infoDict);
    //(将根数组写入沙盒文件中)
    if ([rootArr writeToFile:path atomically:YES]) {
        NSLog(@"plist存储成功");
        NSLOG_DOCUMENTS_PATH;
        
        [MBProgressHUD showSuccess:@"创建成功,请刷新列表"];
        
        [self performSelector:@selector(remove) withObject:nil afterDelay:1.0f];
        
    }else{
        NSLog(@"plist存储失败");
        [MBProgressHUD showError:@"创建失败"];
        return;
    }

    
    
 
}
//查询操作
//+ (NSMutableArray *)readOfUserId:(NSString *)userId{
+ (NSMutableArray *)read{
    //路径
    NSString * path = [DOCUMENT_PATH stringByAppendingString:[NSString stringWithFormat:@"%@UserNovelsPlistList.plist",[AVUser currentUser].objectId]];
    //数据
    NSMutableArray * datas = [NSMutableArray arrayWithContentsOfFile:path];
    NSMutableArray * dataEnd = [@[] mutableCopy];
    
    if (!datas || datas.count == 0 ) {
         NSLog(@"然而还没有数据。/(ㄒoㄒ)/~~");
    }else{
        
        for (int i = 0; i < datas.count; i ++) {
            if ([datas[i][@"userId"]isEqualToString:[AVUser currentUser].objectId]) {
                [dataEnd addObject:datas[i]];
            }
        }
        NSLog(@"%@===数据~%@",NSStringFromSelector(_cmd),dataEnd);
    }
    
    return dataEnd;
}


- (NSArray *)read{
    //路径
    NSString * path = [DOCUMENT_PATH stringByAppendingString:[NSString stringWithFormat:@"%@UserNovelsPlistList.plist",[AVUser currentUser].objectId]];
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray * dataEnd = [@[] mutableCopy];
  
    if (!datas || datas.count == 0 ) {
        NSLog(@"然而还没有数据。/(ㄒoㄒ)/~~");
    }else{
        
        for (int i = 0; i < datas.count; i ++) {
            if ([datas[i][@"userId"]isEqualToString:[AVUser currentUser].objectId]) {
                [dataEnd addObject:datas[i]];
            }
        }
        NSLog(@"%@===数据~%@",NSStringFromSelector(_cmd),dataEnd);
    }
    
    return dataEnd;
}


//删除操作
+ (NSMutableArray *)deleteNovelOfIndexPathRow:(NSInteger)indexPathrow{
    
    /**< 先查询 */
    //路径
    NSString * path = [DOCUMENT_PATH stringByAppendingString:[NSString stringWithFormat:@"%@UserNovelsPlistList.plist",[AVUser currentUser].objectId]];
    //数据
   
    NSMutableArray * datas = [NSMutableArray arrayWithContentsOfFile:path];
    
    if (datas && datas.count > 0) { //从文件删除数组
        //数据存在~移除数据
        
        //得到元素
        //删元素
        NSLog(@"indexPathrow%ld删除的源--%@",(long)indexPathrow,datas[indexPathrow]);
        [datas removeObjectAtIndex:indexPathrow];
        //从写入plist
        [datas writeToFile:path atomically:YES];
        return datas;
       
    }else{ //数据不存在~无需操作数据
        NSLog(@"plist为空，删除失败");
        return nil;
    }

     
}

//从小说plist删除某个小说
+ (NSMutableArray *)deleteNovelOfNovelId:(NSString *)novelId
                                  userId:(NSString *)userId{
    
    //路径
    NSString * path = [DOCUMENT_PATH stringByAppendingString:[NSString stringWithFormat:@"%@UserNovelsPlistList.plist",[AVUser currentUser].objectId]];
    NSMutableArray *arr = [self read];
    
    if (arr && arr.count > 0) {
       
        for (int i = 0;  i < arr.count; i ++) {
            if ([novelId isEqualToString:arr[i][@"novelId"]]  && [[AVUser currentUser].objectId isEqualToString:userId]) {
                [arr removeObjectAtIndex:i];
            }else{
                NSLog(@"非用户操作");
            }
        }
        
        [arr writeToFile:path atomically:YES];
        
    }else{
        NSLog(@"空");
    }
    return arr;
}


//服务器同步
- (void)networkSynchronization{
    
    
    
}




//界面跳转
- (void)remove{
    
    //界面删除
    [self removeFromParentViewController];
    [self.view removeFromSuperview];
}


#pragma mark --  ControllerDelegate> & <UINavigationControllerDelegate> --
#pragma mark --

// 用户选择了某个媒体
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary <NSString *,id> *)info {
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        
        if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
            UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
            
            [_pic setBackgroundImage:originalImage forState:UIControlStateNormal];
            _btnImage = originalImage;
            
            
        }
    }else {
        [_pic setBackgroundImage:info[UIImagePickerControllerEditedImage] forState:UIControlStateNormal];
        
        _btnImage = info[UIImagePickerControllerEditedImage];
    }
    
    //本地
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



#pragma mark -- getter --
#pragma mark --

- (UIAlertController *)alertController{
    
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                _imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                _imagePickerController.mediaTypes = @[mediatypes[0]];
                _imagePickerController.delegate = self;
                _imagePickerController.allowsEditing = YES;
                [self presentViewController:_imagePickerController animated:YES completion:nil];
            }
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //获取支持的媒体格式
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            // 判断是否支持需要设置的sourceType
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                // 1、设置图片拾取器上的sourceType
                _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                // 2、设置支持的媒体格式
                _imagePickerController.mediaTypes = @[mediatypes[0]];
                // 3、是否进入编辑状态
                _imagePickerController.allowsEditing = YES;
                // 4、设置代理
                _imagePickerController.delegate = self;
                [self presentViewController:_imagePickerController animated:YES completion:nil];
            } else {
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"系统模拟器暂不能提供照相功能" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
            } }];
        
        
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消头像");
        }];
        
        
        [_alertController addAction:action1];
        [_alertController addAction:action2];
        [_alertController addAction:action3];
        
    }
    return _alertController;
}



@end
